 //
//  DoubleBallViewController.m
//  MINFOBBS
//
//  Created by 蔡龙生 on 13-11-26.
//  Copyright (c) 2013年 minfo. All rights reserved.
//

#import "DoubleBallViewController.h"
#import "SBJsonParser.h"
#import "DoubleBallCell.h"
#import "DoubleDetailViewController.h"
#import "DetectionSystemVersion.h"
#import "UIColor+expanded.h"
#import "MainSearchViewController.h"
#import "WebSaleCaiController.h"
@interface DoubleBallViewController ()

@end

@implementation DoubleBallViewController
@synthesize doubleBalls;
- (void)viewDidLoad
{
    [super viewDidLoad];
    if (self.isSelf) {
        
    }
    else{
        [self BackButton];
        self.table.showsVerticalScrollIndicator=YES;
        self.table.bounces=YES;
//        NSLog(@"%@",self.query);
        [ self GetWeatherSearch:self.query Location:self.city];
    }
    //[ self GetWeatherSearch:@"双色球" Location:@"上海"];
    }
-(void)BackButton{
    self.navigationItem.titleView=[DetectionSystemVersion SetBarTitle:@"百事搜"];
    [self.navigationItem setHidesBackButton:YES];
    UIButton *btnBack=[[DetectionSystemVersion alloc]BackButton];
    [btnBack addTarget:self action:@selector(BackReturn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem=backItem;
    
}
#pragma mark 导航栏按钮事件
-(void)BackReturn:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - Get Lottery Ticket Data
-(void)GetWeatherSearch:(NSString*)Query Location:(NSString*)City{
    tRequest=[[[ScreenAccess alloc]init]ASIGetSearch:Query  Start:0 Limit:10];
    [tRequest setDelegate:self];
    [tRequest setUsername:@"doubleColorBall"];
}

-(void)requestFinished:(ASIHTTPRequest*)request{
    NSString *response = [request responseString];
    SBJsonParser * parser = [[SBJsonParser alloc] init];
    NSMutableDictionary *Result = [parser objectWithString:response];
    
    if ([request.username isEqual:@"doubleColorBall"]){
        BOOL IsSuccess=[[[Result objectForKey:@"Response"]objectForKey:@"status"]integerValue]==200?YES:NO;
        if (IsSuccess==YES) {
            NSMutableArray *arrReturn=[[NSMutableArray alloc] init];
            [arrReturn addObject:[[Result objectForKey:@"Response"] objectForKey:@"Categories"]];
            for (int i=0; i<arrReturn.count; i++) {
                NSArray *arr=[[arrReturn objectAtIndex:i] objectForKey:@"Category"];
                for (int j=0; j<arr.count; j++) {
                    if([[[arr objectAtIndex:j] objectForKey:@"Entrance"] isEqual:@"Lotto.GetLotto"])
                    {
                        NSArray *itemReturn=[[NSArray alloc] init];
                        itemReturn=[[[arr objectAtIndex:j] objectForKey:@"Items"] objectForKey:@"Item"];
                        for (int k=0; k<itemReturn.count; k++) {
                            if(doubleBalls==nil){
                                doubleBalls=[[NSMutableArray alloc] init];
                            }
                            [doubleBalls addObject:[itemReturn objectAtIndex:k]];
                        }
                    }
                }
            }
        }
        [self.table reloadData];
    }
}

-(void)requestFailed:(ASIHTTPRequest*)request{
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isSelf) {
        return 1;
    }
    else{
    NSArray *list=[[[doubleBalls objectAtIndex:0] objectForKey:@"Properties"] objectForKey:@"Property"];
    NSInteger lotteryCount=[[[list objectAtIndex:0] objectForKey:@"text"]integerValue];
    if(lotteryCount>0){
        return lotteryCount;
    }
    else{
        return 0;
    }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *list=[[[doubleBalls objectAtIndex:0] objectForKey:@"Properties"] objectForKey:@"Property"];
    static NSString *CustomCellIdentifier = @"DoubleBallCell";
    
    NSUInteger row=[indexPath row];
    DoubleBallCell *cell=(DoubleBallCell *) [tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if(cell==nil){
        cell=[[[NSBundle mainBundle] loadNibNamed:CustomCellIdentifier owner:self options:nil] objectAtIndex:0];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleGray;
    cell.imgBall.image=[UIImage imageNamed:[[doubleBalls objectAtIndex:0] objectForKey:@"Title"]];
    cell.nameLbl.text=[[list objectAtIndex:1] objectForKey:@"text"];//彩票名称
    NSString * winNums =[[list objectAtIndex:row*7+4] objectForKey:@"text"];//开奖号码
    NSArray  * winningNum= [winNums componentsSeparatedByString:@","];
    for (int i=0; i<winningNum.count; i++) {
        UIImageView *imgCell=[[UIImageView alloc]initWithFrame:CGRectMake(6+i*28, 0, 26, 26)];
        [imgCell setClipsToBounds:YES];
        [imgCell setContentMode:UIViewContentModeScaleAspectFit];
        imgCell.image=[UIImage imageNamed:@"ball_red"];
        
        UILabel *winNumLbl=[[UILabel alloc] initWithFrame:CGRectMake(6+i*28, 0, 26, 26)];
        winNumLbl.text=[winningNum objectAtIndex:i];
        winNumLbl.textColor=[UIColor whiteColor];
        winNumLbl.backgroundColor=[UIColor clearColor];
        winNumLbl.textAlignment=NSTextAlignmentCenter;
        winNumLbl.font=[UIFont systemFontOfSize:18];
        
        [cell.cusView addSubview:imgCell];
        [cell.cusView addSubview:winNumLbl];
    }
//    cell.rolloverLbl.text=@"";
//    cell.detailLbl.text=@"详情";
//    cell.clickLbl.text=@"立即投注";
    [cell.btnSend addTarget:self action:@selector(PressWeb:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btnSend setTitle:[[list objectAtIndex:list.count-2] objectForKey:@"text"] forState:UIControlStateNormal];
    NSString *issueNum=[[list objectAtIndex:row*7+2] objectForKey:@"name"];//彩票期号
    issueNum =[issueNum stringByReplacingOccurrencesOfString:@"彩票期号" withString:@"期"];
    cell.issueNumberLbl.text=issueNum;

    NSString *drawDate=[[list objectAtIndex:row*7+3] objectForKey:@"text"];//开奖日期
    cell.dateLbl.text=[self DateFormat:drawDate];
    
    return cell;
}
-(void)PressWeb:(UIButton *)button{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:button.currentTitle]];
//    NSLog(@"%@",button.currentTitle);
    WebSaleCaiController *webCon=[[WebSaleCaiController alloc]init];
    webCon.requestUrl=request;
    if (self.isSelf) {
        [ [self menuContainerViewController].navigationController  pushViewController:webCon animated:YES];
    }
    else{
        [self.navigationController pushViewController:webCon animated:YES];
    }
}
//日期格式转换
-(NSString *)DateFormat:(NSString *)Date{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate* inputDate = [inputFormatter dateFromString:Date];
    
    NSDateFormatter *outputFormatter =[[NSDateFormatter alloc] init];
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:@"MM月dd日"];
    NSString *strDate = [outputFormatter stringFromDate:inputDate];
    return strDate;
}

#pragma mark - Table Delegate Methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 138;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row=[indexPath row];
    DoubleDetailViewController *doubleDetailController =[[DoubleDetailViewController alloc] init];
    doubleDetailController.issueIndex=row;
    doubleDetailController.city=self.city;
    doubleDetailController.doubleBalls=doubleBalls;
    doubleDetailController.lotteryIndex=self.lotteryIndex;
    if (self.isSelf) {
         [ [self menuContainerViewController].navigationController  pushViewController:doubleDetailController animated:YES];
    }
    else{
    [self.navigationController pushViewController:doubleDetailController animated:YES];
    }
}


-(float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.isSelf) {
        return 38;
    }
    return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *result;
    result=[[UIView alloc]init];
    result.backgroundColor=[UIColor clearColor];
    if (self.isSelf) {
        UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.table.frame.size.width, 3)];
        img.image=[UIImage imageNamed:@"footLine"];
        UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 3, self.table.frame.size.width, 35)];
        [btn setTitle:@"点击历史中奖号码" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(PrseeMore) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitleColor:[UIColor colorWithHexString:@"0xb7b7b7"] forState:UIControlStateNormal];
        btn.titleLabel.font=[UIFont systemFontOfSize:14];
        [result addSubview:btn];
        [result addSubview:img];
    }
    return result;
}

- (MainSearchViewController *)menuContainerViewController {
    return (MainSearchViewController *)self.parentViewController;
}
-(void)PrseeMore{
    //    if (self.isSelf) {
    DoubleBallViewController *jokecon=[[DoubleBallViewController alloc]init];
    NSString *str=[[doubleBalls objectAtIndex:0] objectForKey:@"href"];
    NSRange range = [str rangeOfString:@"query="];
    str=[str substringFromIndex:range.location +range.length];
    jokecon.query=str;
    [ [self menuContainerViewController].navigationController  pushViewController:jokecon animated:YES];
    //    }
    
    
}
@end
